<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !modifyInfo.visible &&
        !deviceDetailInfo.visible &&
        !deviceModifyInfo.visible &&
        !saleDeviceDetailInfo.visible &&
        !saleDetailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :clear-type="clearType"
          :filter-btn="filterInfo.searchBtn"
          :filter-list="filterInfo.searchList"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-addSaleOrder>
            <el-button @click="addSaleOrder()">销售单导入</el-button>
            <el-button
              :disabled="btnShipment"
              style="margin-right: 5px"
              @click="shipment"
              >发货</el-button
            >
            <el-button
              :disabled="canPrint"
              style="margin-right: 5px"
              @click="printCode"
              >打印二维码</el-button
            >
            <el-button
              :disabled="canGenerate"
              style="margin-right: 5px"
              @click="generateCode"
              >生成二维码</el-button
            >
            <el-button style="margin-right: 5px" @click="printProductCode"
              >打印产品码</el-button
            >
          </template>
        </NewPageFilter>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getDeliverOrder"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :check-box="true"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo || '-'
          }}</span>
        </template>
        <template v-slot:col-saleNo="scope">
          <span class="slip-edit" @click="showsaleNoDetail(scope.row)">{{
            scope.row.saleNo
          }}</span>
        </template>
      </TableContainer>
    </div>
    <AddSaleOrder
      v-if="addSaleOrderDialog.visible"
      v-model:show-dialog="addSaleOrderDialog.visible"
      :highlight-row="true"
      @callback="addSaleOrderBack"
    />
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :sale-order-id="modifyInfo.saleOrderId"
      :order-id="modifyInfo.orderId"
      @returnModify="getList"
    />
    <DeviceModify
      v-if="deviceModifyInfo.visible"
      v-model:visible="deviceModifyInfo.visible"
      :sale-order-id="deviceModifyInfo.saleOrderId"
      :order-id="deviceModifyInfo.orderId"
      @returnModify="getList"
    />
    <detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      @returnDetail="getList"
    />
    <DeviceDetail
      v-if="deviceDetailInfo.visible"
      :id="deviceDetailInfo.id"
      v-model:visible="deviceDetailInfo.visible"
      @returnDetail="getList"
    />
    <SaleDetail
      v-if="saleDetailInfo.visible && !modifyInfo.visible"
      :id="saleDetailInfo.id"
      v-model:visible="saleDetailInfo.visible"
    />
    <SaleDeviceDetail
      v-if="saleDeviceDetailInfo.visible"
      :id="saleDeviceDetailInfo.id"
      v-model:visible="saleDeviceDetailInfo.visible"
    />
    <ChosePrinter :visible="printerInfo.visible" @callBack="printerCallBack" />
  </div>
</template>
<script setup name="deliverOrder">
import AddSaleOrder from './addSaleOrder'
import modify from './modify'
import DeviceModify from './deviceModify'
import detail from './detail'
import DeviceDetail from './deviceDetail'
import SaleDetail from './../../sale/saleOrder/detail'
import SaleDeviceDetail from './../../sale/saleOrder/deviceDetail'
import {
  getDeliverOrder,
  shipmentsGoods,
  printQrCodeDeliverOrder,
  generateCodeDeliverOrder,
  deliverOrderValidateLicense,
  deliverOrderDetailInvalid,
  deleteDeliverOrder,
  deliverOrderProductCodePrint,
} from '@/api/supplier.js'
const route = useRoute()
const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
  copyQuery: {},
  query: {
    sort: 'order_no desc',
    status: '',
    deliverProductType: '',
    orderNoLike: '',
    saleNoLike: '',
  },
  searchList: [
    {
      label: '状态',
      value: 'status',
      componentType: 'select-model',
      code: 'deliver_order_status',
      event: search,
      clearable: true,
    },
    {
      label: '发货单类型',
      value: 'deliverProductType',
      componentType: 'select-model',
      code: 'order_product_type',
      event: search,
      clearable: true,
    },
    {
      componentType: 'input',
      label: '发货单',
      value: 'orderNoLike',
      clearable: true,
      event: search,
    },
    {
      componentType: 'input',
      label: '销售单',
      value: 'saleNoLike',
      clearable: true,
      event: search,
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'addSaleOrder',
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '发货单号', value: 'orderNo', type: 'slot' },
    { label: '销售单号', value: 'saleNo', type: 'slot' },
    { label: '状态', value: 'statusValue' },
    { label: '发货单类型', value: 'deliverProductTypeValue' },
    { label: '客户名称', value: 'hospitalName' },
    { label: '创建人', value: 'orgName' },
    { label: '创建时间', value: 'createTime' },
    { label: '预计发货时间', value: 'expectedDeliverTime' },
    { label: '是否生成二维码', value: 'hasQrCodeName' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '发货',
        event: shipment,
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: updated,
        show: true,
        ifRender: function (row) {
          return row.status === 1 && row.hasQrCode === 0
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: function (row) {
          return row.status === 1
        },
      },

      {
        label: '作废',
        event: invalid,
        show: true,
        ifRender: function (row) {
          return row.status === 2
        },
      },
    ],
  },
})
const printerInfo = ref({
  visible: false,
  data: {},
})
//修改或新增弹框信息
const modifyInfo = ref({
  visible: false,
  saleOrderId: '',
  orderId: '',
})
const deviceModifyInfo = ref({
  visible: false,
  saleOrderId: '',
  orderId: '',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const deviceDetailInfo = ref({
  visible: false,
  id: '',
})
const saleDetailInfo = ref({
  visible: false,
  id: '',
})
const saleDeviceDetailInfo = ref({
  visible: false,
  id: '',
})
const addSaleOrderDialog = ref({
  visible: false,
})
const clearType = ref(true)
const btnShipment = computed(() => {
  let arr = tableInfo.value.selections
  let flag = false
  if (arr.length) {
    flag = !arr.filter((item) => item.status !== 1).length
  }
  return !flag
})
const canPrint = computed(() => {
  let arr = tableInfo.value.selections
  let flag = false
  if (arr.length) {
    flag = !arr.filter(
      (item) => item.hasQrCode !== 1 || item.deliverProductType !== 1
    ).length
  }
  return !flag
})
const canGenerate = computed(() => {
  let arr = tableInfo.value.selections
  let flag = false
  if (arr.length) {
    flag = !arr.filter(
      (item) => item.hasQrCode !== 0 || item.deliverProductType !== 1
    ).length
  }
  return !flag
})
watch(
  () => route,
  async (val) => {
    const params = val.params
    if (val.name === 'deliverOrder') {
      if (await Object.keys(params).length) {
        modifyInfo.value.visible = false
        modifyInfo.value.saleOrderId = ''
        modifyInfo.value.orderId = ''
        deviceModifyInfo.value.visible = false
        deviceModifyInfo.value.saleOrderId = ''
        deviceModifyInfo.value.orderId = ''
        if (await params.id) {
          if (params.saleProductType == 1) {
            modifyInfo.value.saleOrderId = params.id
            modifyInfo.value.orderId = ''
            modifyInfo.value.visible = true
          } else if (params.saleProductType == 2) {
            deviceModifyInfo.value.saleOrderId = params.id
            deviceModifyInfo.value.orderId = ''
            deviceModifyInfo.value.visible = true
          }
          addSaleOrderDialog.value.visible = false
          detailInfo.value.visible = false
          detailInfo.value.id = ''
          deviceDetailInfo.value.visible = false
          deviceDetailInfo.value.id = ''
          printerInfo.value.visible = false
          printerInfo.value.id = ''
        }
      }
    }
  },
  { immediate: true, deep: true }
)

function addSaleOrder() {
  addSaleOrderDialog.value.visible = true
}
function addSaleOrderBack(data) {
  proxy.$nextTick(() => {
    addSaleOrderDialog.value.visible = false
    if (data && data.orderNo) {
      if (data.saleProductType == 1) {
        modifyInfo.value.visible = true
        modifyInfo.value.saleOrderId = data.id
        modifyInfo.value.orderId = ''
      } else if (data.saleProductType == 2) {
        deviceModifyInfo.value.visible = true
        deviceModifyInfo.value.saleOrderId = data.id
        deviceModifyInfo.value.orderId = ''
      }
    }
  })
}
function updated(row) {
  if (row.deliverProductType == 1) {
    modifyInfo.value.saleOrderId = ''
    modifyInfo.value.orderId = row.id
    modifyInfo.value.visible = true
  } else if (row.deliverProductType == 2) {
    deviceModifyInfo.value.saleOrderId = ''
    deviceModifyInfo.value.orderId = row.id
    deviceModifyInfo.value.visible = true
  }
}
function remove(row) {
  deleteDeliverOrder([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function invalid(row) {
  let ids = [row.id]
  deliverOrderDetailInvalid(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//查看明细
function showDetail(row) {
  if (row.deliverProductType == 1) {
    detailInfo.value.id = row.id
    detailInfo.value.visible = true
  } else if (row.deliverProductType == 2) {
    deviceDetailInfo.value.id = row.id
    deviceDetailInfo.value.visible = true
  }
}
//查看采购单明细
function showsaleNoDetail(row) {
  if (row.deliverProductType == 1) {
    saleDetailInfo.value.id = row.saleId
    saleDetailInfo.value.visible = true
  } else if (row.deliverProductType == 2) {
    saleDeviceDetailInfo.value.id = row.saleId
    saleDeviceDetailInfo.value.visible = true
  }
}
function shipment(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => {
      return item.id
    })
  }
  deliverOrderValidateLicense(ids).then((resp) => {
    if (resp && resp.success) {
      shipmentsGoods(ids).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    }
  })
}
function printCode() {
  if (!tableInfo.value.selections.length) {
    proxy.$message({
      message: '请至少选择一条数据操作',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }

  let ids = tableInfo.value.selections.map((value) => value.id)
  printQrCodeDeliverOrder(ids).then((resp) => {
    if (resp && resp.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = resp.data
    }
  })
}
function generateCode() {
  if (!tableInfo.value.selections.length) {
    proxy.$message({
      message: '请至少选择一条数据操作',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let ids = tableInfo.value.selections.map((value) => value.id)
  generateCodeDeliverOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function printProductCode() {
  if (!tableInfo.value.selections.length) {
    proxy.$message({
      message: '请至少选择一条数据操作',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let ids = tableInfo.value.selections.map((value) => value.id)
  deliverOrderProductCodePrint(ids).then((resp) => {
    if (resp && resp.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = resp.data
    }
  })
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  getList()
}

onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
  getList()
})
</script>

<style scoped lang="scss">
:deep(.el-table) .warning-row {
  background: #f5e4e4;
}

:deep(.el-table__body)
  tr.hover-row
  > td:not(.el-table-fixed-column--right, .el-table-fixed-column--left) {
  background-color: transparent !important;
}
</style>
